<template>
  <div class="app-container">

    <!-- 课程信息表单 -->
    <el-form
      label-width="120px"
      :model="courseInfo"
      ref="courseForm"
      :rules="courseRules"
    >
      <el-form-item
        label="课程标题"
        prop="title"
      >
        <el-input
          v-model="courseInfo.title"
          placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
        />
      </el-form-item>
      <!-- 课程讲师 TODO -->
      <el-form-item
        label="课程讲师"
        prop="teacherId"
      >
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择讲师"
        >
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 课程分类： 级联下拉列表 -->
      <el-form-item
        label="课程类别"
        prop="subjectId"
      >
        <!-- 一级联动 -->
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="请选择"
          @change="subjectChanged"
        >
          <el-option
            v-for="subject in subjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>

        <!-- 二级分类 -->
        <el-select
          v-model="courseInfo.subjectId"
          placeholder="请选择"
        >
          <el-option
            v-for="subject in subjectLevelTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>
      <!-- 所属分类 TODO -->
      <el-form-item
        label="总课时"
        prop="lessonNum"
      >
        <el-input-number
          :min="0"
          :max="999"
          :step="1"
          step-strictly
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>
      <!-- 课程简介 TODO -->
      <el-form-item
        label="课程简介"
        prop="description"
      >
        <tinymce
          :height="300"
          v-model="courseInfo.description"
        />
      </el-form-item>
      <!-- 课程封面 TODO -->
      <el-form-item
        label="课程封面"
        prop="cover"
      >
        <el-upload
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :on-error="handleCoverError"
          class="cover-uploader"
          action="http://localhost:8120/admin/oss/file/upload?module=cover"
        >
          <img
            v-if="courseInfo.cover"
            :src="courseInfo.cover"
          >
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
          />
        </el-upload>
      </el-form-item>

      <el-form-item
        label="课程价格"
        prop="price"
      >
        <el-input-number
          :min="0"
          :max="999999"
          :precision="2"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        /> 元
      </el-form-item>
    </el-form>
    <!-- 课程信息表单 TODO -->
    <div style="text-align:center;">
      <el-button
        type="primary"
        :disabled="saveBtnDisabled"
        @click="saveAndNext()"
      >保存并下一步</el-button>
    </div>
  </div>
</template>
<script>
import { CourseApi } from '@/api/course/url-course'
import { TeacherApi } from '@/api/edu/url-teacher'
import { SubjectApi } from '@/api/subject/url-subject'
// 富文本编辑器
import Tinymce from '@/components/Tinymce'
import { postAction, getAction, putAction } from '@/api/manage'
export default {
  components: { Tinymce },
  data() {
    return {
      //按钮是否禁用
      saveBtnDisabled: false,
      // 基本数据信息
      courseInfo: {
        price: 0,
        lessonNum: 0,
        // 以下解决表单数据不全时insert语句非空校验
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        cover: '',
        description: ''
      },
      // 讲师列表
      teacherList: [],
      // 课程一级列表
      subjectList: [],
      // 课程二级列表
      subjectLevelTwoList: [],
      courseRules: {
        title: [
          {
            required: true, //是否必填
            message: '标题不能为空', //规则
            trigger: 'blur'  //何事件触发
          },
          //可以设置双重验证标准
          { max: 30, message: '长度在30个字符内', }
        ],
        teacherId: [{ required: true, message: '请选择讲师', trigger: 'blur' },],
        subjectId: [{ required: true, message: '请选择课程类别', trigger: 'blur' },],
        lessonNum: [{ required: true, message: '请填写总课时数', trigger: 'blur' },],
        cover: [{ required: true, message: '请添加课程封面', trigger: 'blur' },],
        price: [{ required: true, message: '请添加课程价格', trigger: 'blur' },],
      }
    }
  },
  created() {
    // courseId来源于路由
    if (this.$route.name === 'CourseInfoEdit') {
      this.$parent.courseId = this.$route.params.id
      this.active = 0
    }

    if (this.$route.name === 'CourseChapterEdit') {
      this.$parent.courseId = this.$route.params.id
      this.active = 1
    }

    // courseId 来源于父组件
    if (this.$parent.courseId) {
      this.fetchCourseInfoById(this.$parent.courseId)
    } else {
      // 新增: 只需要渲染一级类别
      this.initSubjectList()
    }

    this.initTeacherList()
  },
  methods: {
    // 根据id获取课程基本信息
    fetchCourseInfoById(id) {
      getAction(CourseApi.getCourseInfoById, { id: id }).then(res => {
        this.courseInfo = res.data.item

        // 课程类别渲染
        getAction(SubjectApi.list).then(res => {
          this.subjectList = res.data.items

          // 填充二级菜单，遍历一级菜单
          this.subjectList.forEach(subject => {
            // 找到和courseInfo.subjectParentId 一致的父类别记录
            if (subject.id === this.courseInfo.subjectParentId) {
              // 拿到当前类别下的子类别列表 ，将子类别列表填入二级下拉菜单列表
              this.subjectLevelTwoList = subject.children
            }
          })
        })
      })
    },
    // 获取讲师列表
    initTeacherList() {
      getAction(TeacherApi.listAll).then((res) => {
        this.teacherList = res.data.items
      })
    },
    // 初始化分类列表
    initSubjectList() {
      getAction(SubjectApi.list).then(res => {
        this.subjectList = res.data.items
      })
    },
    // 切换一级下拉列表
    subjectChanged(value) {
      // 遍历一级类别
      this.subjectList.forEach(subject => {
        // 判断当前选中的一级类别是否和当前遍历的一级类别id一致
        if (subject.id === value) {
          //切换时清二级列表
          this.courseInfo.subjectId = ''
          this.subjectLevelTwoList = subject.children
        }
      })
    },
    // 保存并下一步
    saveAndNext() {
      this.saveBtnDisabled = true
      if (!this.$parent.courseId) {
        this.saveData()
      } else {
        this.updateData()
      }
    },
    // 保存课程基本信息
    saveData() {
      this.$refs.courseForm.validate(val => {
        if (val) {
          postAction(CourseApi.saveCourseInfo, this.courseInfo).then(res => {
            this.$message.success(res.message)
            // 获取courseId
            this.$parent.courseId = res.data.courseId
            // 访问父组件的成员
            this.$parent.active = 1
          })
        } else {
          this.saveBtnDisabled = false
        }
      })
    },
    // 修改用户基本信息
    updateData() {
      this.$refs.courseForm.validate(val => {
        if (val) {
          putAction(CourseApi.updateCourseInfoById, this.courseInfo).then(res => {
            this.$message.success(res.message)
            this.$parent.active = 1
          })
        } else {
          this.saveBtnDisabled = false
        }
      })
    },
    // 上传成功回调
    handleCoverSuccess(res, file) {
      if (res.success) {
        this.courseInfo.cover = res.data.url
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error("上传失败！")
      }
    },
    // 上传校验
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式！')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB！')
      }
      return isLt2M && isJPG
    },
    // 错误处理
    handleCoverError() {
      this.$message.error("上传失败(http错误)！")
    }
  }
}
</script>
<style>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409eff;
}
.cover-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 640px;
  height: 357px;
  line-height: 357px;
  text-align: center;
}
.cover-uploader img {
  width: 640px;
  height: 357px;
  display: block;
}
</style>